package com.aba.im.ui;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class ChatServer {
    // 存储在线用户的Socket和用户名映射
    private static Map<String, Socket> onlineUsers = new HashMap<>();
    // 服务器监听端口
    private static final int PORT = 8888;

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器已启动，等待客户端连接...");
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("有客户端连接");
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket clientSocket) {
        try (Scanner in = new Scanner(clientSocket.getInputStream());
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
            // 接收用户名
            String username = in.nextLine();
            onlineUsers.put(username, clientSocket);
            System.out.println(username + " 已上线");

            while (true) {
                String message = in.nextLine();
                // 简单协议：MSG|发送者|接收者|消息内容
                if (message.startsWith("MSG|")) {
                    String[] parts = message.split("\\|");
                    String sender = parts[1];
                    String receiver = parts[2];
                    String msgContent = parts[3];
                    Socket receiverSocket = onlineUsers.get(receiver);
                    if (receiverSocket != null) {
                        PrintWriter receiverOut = new PrintWriter(receiverSocket.getOutputStream(), true);
                        receiverOut.println("PRIVATE_MSG|" + sender + "|" + msgContent);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            onlineUsers.values().remove(clientSocket);
            System.out.println("有客户端下线");
        }
    }
}

